package com.desmart.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.desmart.util.PropertiesUtil;
import com.geetest.sdk.GeetestLib;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;


/**
 * Servlet implementation class Login
 */
@WebServlet("/login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/text");
		response.setCharacterEncoding("UTF-8");
		GeetestLib gtSdk = new GeetestLib(PropertiesUtil.getPropertyString("geetest_id"), PropertiesUtil.getPropertyString("geetest_key"), 
				PropertiesUtil.getPropertyBoolean("newfailback"));
		String resStr = "{}";
		String userid = "uim";
		
		//自定义参数,可选择添加
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("user_id", userid); //网站用户id
		param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
		param.put("ip_address", "127.0.0.1"); //传输用户请求验证时所携带的IP

		//进行验证预处理
		int gtServerStatus = gtSdk.preProcess(param);
		
		//将服务器状态设置到session中
		request.getSession().setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);
		//将userid设置到session中
		request.getSession().setAttribute("userid", userid);
		
		resStr = gtSdk.getResponseStr();

		PrintWriter out = response.getWriter();
		out.println(resStr);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/text");
		response.setCharacterEncoding("UTF-8");
		String challenge = request.getParameter(GeetestLib.fn_geetest_challenge);
		String validate = request.getParameter(GeetestLib.fn_geetest_validate);
		String seccode = request.getParameter(GeetestLib.fn_geetest_seccode);
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		PrintWriter out = response.getWriter();
		JSONObject data = new JSONObject();
		try {
			if(username != null && !"".equals(username)) {
				if(password != null && !"".equals(password)) {
					if(password.equals("123456")) {
						GeetestLib gtSdk = new GeetestLib(PropertiesUtil.getPropertyString("geetest_id"), PropertiesUtil.getPropertyString("geetest_key"), 
								PropertiesUtil.getPropertyBoolean("newfailback"));
						//从session中获取gt-server状态
						int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
						//从session中获取userid
						String userid = (String)request.getSession().getAttribute("userid");
						//自定义参数,可选择添加
						HashMap<String, String> param = new HashMap<String, String>(); 
						param.put("user_id", userid); //网站用户id
						param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
						param.put("ip_address", "127.0.0.1"); //传输用户请求验证时所携带的IP
						int gtResult = 0;
						if (gt_server_status_code == 1) {
							//gt-server正常，向gt-server进行二次验证
							gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
							System.out.println(gtResult);
						} else {
							// gt-server非正常情况下，进行failback模式验证
							System.out.println("failback:use your own server captcha validate");
							gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
							System.out.println(gtResult);
						}
						if (gtResult == 1) {
							// 验证成功
							data.put("status", "success");
							data.put("msg", "验证通过");
						} else {
							// 验证失败
							data.put("status", "fail");
							data.put("msg", "验证码错误");
						}
						
					} else {
						data.put("status", "fail");
						data.put("msg", "密码错误");
					}
				} else {
					data.put("status", "fail");
					data.put("msg", "请输入密码");
				}
			} else {
				data.put("status", "fail");
				data.put("msg", "请输入用户名");
			}
			out.println(JSONObject.fromObject(data));
			out.flush();
			out.close();
			return;
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
